<?php
namespace App\Admin\Actions\Grid\Mp;

use App\Lib\WeApp\WeApp;
use App\Models\Mp\WxMpFreePublish;
use Dcat\Admin\Grid\RowAction;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Model;

class FreePublishMaterialAction extends RowAction
{

    /**
     * 标题
     *
     * @return string
     */
    public function title()
    {
        if($this->row->parent_id === 0){
            if(!_empty_($this->row->media_id)){
                return '更新草稿';
            }else{
                if(!_empty_($this->row->article_id)){
                    return '重发草稿';
                }else{
                    return '新增草稿';
                }
            }
        }else{

        }
    }

    /**
     * 设置确认弹窗信息，如果返回空值，则不会弹出弹窗
     *
     * 允许返回字符串或数组类型
     *
     * @return array|string|void
     */
    public function confirm()
    {
        if($this->row->parent_id === 0) {
            if (!_empty_($this->row->media_id)) {
                return [
                    // 确认弹窗 title
                    "确定修改这个对应的公众号草稿吗？",
                    // 确认弹窗 content
                    $this->row->title,
                ];
            } else {
                return [
                    // 确认弹窗 title
                    "确定新增一个公众号草稿吗？",
                    // 确认弹窗 content
                    $this->row->title,
                ];
            }
        }
        return '';
    }

    /**
     * 处理请求
     *
     * @param Request $request
     *
     * @return \Dcat\Admin\Actions\Response
     */
    public function handle(Request $request)
    {
        // 获取当前行ID
        $id = $this->getKey();
        $free_publish = WxMpFreePublish::find($id);
        if($free_publish->parent_id === 0){
            $weapp = new WeApp('mp');
            $mp = $weapp->getMpServicer();
            if(_empty_($free_publish->media_id)){
                $res = $mp->addOrUpdateDraft($free_publish->id);
            }else{
                $mp->addOrUpdateDraft($free_publish->id);
                WxMpFreePublish::where('parent_id', $free_publish->id)->orderBy('order', 'asc')->orderBy('id', 'asc')->map(function ($v) use (&$mp){
                    try {
                        $mp->addOrUpdateDraft($v->id);
                    }catch (\Exception $e){
                        _logger_(__file__, __line__, $e->getMessage());
                    }
                });
            }
            if($res['code'] == 200){
                return $this->response()->success("同步成功")->refresh();
            }else{
                return $this->response()->error($res['msg']);
            }
        }else{
            return $this->response()->warning('不要点子级');
        }
    }

    /**
     * 设置要POST到接口的数据
     *
     * @return array
     */
    public function parameters()
    {
        return [
            'title' => $this->row->title,
        ];
    }
}
